package org.gap.wizards.views;

import java.util.Arrays;
import java.util.List;

import net.slashie.libjcsi.CSIColor;
import net.slashie.libjcsi.CharKey;
import net.slashie.libjcsi.ConsoleSystemInterface;
import net.slashie.libjcsi.textcomponents.MenuBox;

import org.gap.wizards.items.Item;

public class LibJCsiInventorySelectionView implements View, InventorySelectionView {
	private MenuBox<Item> menuBox;
	private final ViewPlatform console;

	public LibJCsiInventorySelectionView(ConsoleSystemInterface csi, ViewPlatform console) {
		this.console = console;
		menuBox = new MenuBox<Item>(csi, MenuBox.MultiSelect);
		menuBox.setBounds(80, 1, 36, 36);
		menuBox.setBorderColor(CSIColor.BLUE);
		menuBox.setBorder(true);
	}
	
	/* (non-Javadoc)
	 * @see org.gap.wizards.views.InventorySelection#setItems(java.util.List)
	 */
	@Override
	public void setItems(List<Item> items) {
		menuBox.setMenuItems(items);
	}
	
	/* (non-Javadoc)
	 * @see org.gap.wizards.views.InventorySelection#getSelection()
	 */
	@Override
	public List<Item> getSelection() {
		draw();
		CharKey keyPressed;
		while ((keyPressed = console.getKeyPressed()).code != CharKey.ENTER) {
			if (keyPressed.code == CharKey.j) {
				menuBox.moveDown();
			} else if (keyPressed.code == CharKey.k) {
				menuBox.moveUp();
			} else if (keyPressed.code == CharKey.SPACE) {
				menuBox.selectCursor();
			}
			draw();
		}
		if (menuBox.getSelected().isEmpty()) {
			return Arrays.asList(menuBox.getItemAtCursor());
		}
		return menuBox.getSelected();
	}

	/* (non-Javadoc)
	 * @see org.gap.wizards.views.InventorySelection#draw()
	 */
	@Override
	public void draw() {
		menuBox.draw();
	}
}
